<!-- 考试管理 -->
<template>
  <div class="app-container">
    <!-- 搜索工具栏 -->
    <div class="toolbar">
      <el-form :inline="true" :model="queryParams" class="search-form">
        <el-form-item label="试卷名称">
          <el-input
            v-model="queryParams.paperName"
            placeholder="试卷名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="科目">
          <el-input
            v-model="queryParams.subject"
            placeholder="科目"
            clearable
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryParams.status" placeholder="状态" clearable>
            <el-option label="未发布" :value="0" />
            <el-option label="已发布" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetQuery">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>

      <div class="toolbar-buttons">
        <el-button type="success" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增试卷
        </el-button>
        <el-button type="primary" @click="handleGenerateByRule">
          <el-icon><Document /></el-icon>
          规则生成
        </el-button>
      </div>
    </div>

    <!-- 试卷列表 -->
    <el-table v-loading="loading" :data="paperList" style="width: 100%">
      <el-table-column
        prop="paperName"
        label="试卷名称"
        show-overflow-tooltip
      />
      <el-table-column prop="subject" label="科目" width="120" />
      <el-table-column prop="totalScore" label="总分" width="80" />
      <el-table-column prop="duration" label="时长(分钟)" width="100" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.status === 0 ? 'warning' : 'success'">
            {{ row.status === 0 ? "未发布" : "已发布" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250" fixed="right">
        <template #default="{ row }">
          <el-button
            v-if="row.status === 0"
            type="primary"
            link
            @click="handleEdit(row)"
          >
            编辑
          </el-button>
          <el-button
            v-if="row.status === 0"
            type="success"
            link
            @click="handlePublish(row)"
          >
            发布
          </el-button>
          <el-button
            v-if="row.status === 1"
            type="info"
            link
            @click="handleViewDetail(row)"
          >
            查看
          </el-button>
          <el-button
            v-if="row.status === 0"
            type="danger"
            link
            @click="handleDelete(row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="800px"
      :close-on-click-modal="false"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="试卷名称" prop="paperName">
          <el-input v-model="form.paperName" placeholder="请输入试卷名称" />
        </el-form-item>
        <el-form-item label="科目" prop="subject">
          <el-input v-model="form.subject" placeholder="请输入科目" />
        </el-form-item>
        <el-form-item label="总分" prop="totalScore">
          <el-input-number
            v-model="form.totalScore"
            :min="1"
            :max="1000"
            controls-position="right"
          />
        </el-form-item>
        <el-form-item label="考试时长" prop="duration">
          <el-input-number
            v-model="form.duration"
            :min="1"
            :max="1000"
            controls-position="right"
          />
          <span class="unit-text">分钟</span>
        </el-form-item>
        <el-form-item label="题目" prop="questions">
          <div class="question-toolbar">
            <el-button type="primary" @click="handleAddQuestion">
              <el-icon><Plus /></el-icon>
              添加题目
            </el-button>
          </div>
          <el-table :data="form.questions" style="width: 100%">
            <el-table-column type="index" label="序号" width="60" />
            <el-table-column
              prop="questionText"
              label="题目内容"
              show-overflow-tooltip
            />
            <el-table-column prop="score" label="分值" width="80" />
            <el-table-column prop="difficulty" label="难度" width="100">
              <template #default="{ row }">
                <el-tag :type="getDifficultyType(row.difficulty)">
                  {{ getDifficultyText(row.difficulty) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100">
              <template #default="{ $index }">
                <el-button
                  type="danger"
                  link
                  @click="handleRemoveQuestion($index)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 选择题目对话框 -->
    <el-dialog
      title="选择题目"
      v-model="questionDialogVisible"
      width="800px"
      :close-on-click-modal="false"
    >
      <div class="question-search">
        <el-form :inline="true" :model="questionQueryParams">
          <el-form-item label="科目">
            <el-input
              v-model="questionQueryParams.subject"
              placeholder="科目"
              clearable
            />
          </el-form-item>
          <el-form-item label="难度">
            <el-select
              v-model="questionQueryParams.difficulty"
              placeholder="难度"
              clearable
            >
              <el-option label="简单" value="EASY" />
              <el-option label="中等" value="MEDIUM" />
              <el-option label="困难" value="HARD" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchQuestions">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-table
        ref="questionTableRef"
        v-loading="questionLoading"
        :data="questionList"
        style="width: 100%"
        @selection-change="handleQuestionSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column
          prop="questionText"
          label="题目内容"
          show-overflow-tooltip
        />
        <el-table-column prop="score" label="分值" width="80" />
        <el-table-column prop="difficulty" label="难度" width="100">
          <template #default="{ row }">
            <el-tag :type="getDifficultyType(row.difficulty)">
              {{ getDifficultyText(row.difficulty) }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
      <div class="question-pagination">
        <el-pagination
          v-model:current-page="questionQueryParams.pageNum"
          v-model:page-size="questionQueryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="questionTotal"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleQuestionSizeChange"
          @current-change="handleQuestionCurrentChange"
        />
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="questionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmSelectQuestions"
            >确定</el-button
          >
        </div>
      </template>
    </el-dialog>

    <!-- 规则生成对话框 -->
    <el-dialog
      title="规则生成试卷"
      v-model="ruleDialogVisible"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="ruleRules"
        label-width="100px"
      >
        <el-form-item label="试卷名称" prop="paperName">
          <el-input v-model="ruleForm.paperName" placeholder="请输入试卷名称" />
        </el-form-item>
        <el-form-item label="科目" prop="subject">
          <el-input v-model="ruleForm.subject" placeholder="请输入科目" />
        </el-form-item>
        <el-form-item label="考试时长" prop="duration">
          <el-input-number
            v-model="ruleForm.duration"
            :min="1"
            :max="1000"
            controls-position="right"
          />
          <span class="unit-text">分钟</span>
        </el-form-item>
        <el-form-item label="题目规则">
          <div
            class="rule-item"
            v-for="(rule, index) in ruleForm.rules"
            :key="index"
          >
            <el-select v-model="rule.difficulty" placeholder="难度">
              <el-option label="简单" value="EASY" />
              <el-option label="中等" value="MEDIUM" />
              <el-option label="困难" value="HARD" />
            </el-select>
            <el-input-number
              v-model="rule.count"
              :min="1"
              :max="100"
              controls-position="right"
              placeholder="题目数量"
            />
            <el-input-number
              v-model="rule.score"
              :min="1"
              :max="100"
              controls-position="right"
              placeholder="每题分值"
            />
            <el-button type="danger" link @click="removeRule(index)">
              删除
            </el-button>
          </div>
          <div class="rule-add">
            <el-button type="primary" link @click="addRule">
              <el-icon><Plus /></el-icon>
              添加规则
            </el-button>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="ruleDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="generatePaper">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getExamPapers,
  addExamPaper,
  updateExamPaper,
  deleteExamPaper,
  publishExamPaper,
  generateExamPaper,
} from "@/api/exam";
import { getQuestions } from "@/api/question";

const router = useRouter();

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  paperName: "",
  subject: "",
  status: "",
});

// 列表数据
const loading = ref(false);
const paperList = ref([]);
const total = ref(0);

// 表单数据
const dialogVisible = ref(false);
const dialogType = ref("add"); // add or edit
const formRef = ref(null);
const form = reactive({
  id: undefined,
  paperName: "",
  subject: "",
  totalScore: 100,
  duration: 60,
  questions: [],
});

// 表单校验规则
const rules = {
  paperName: [{ required: true, message: "请输入试卷名称", trigger: "blur" }],
  subject: [{ required: true, message: "请输入科目", trigger: "blur" }],
  totalScore: [{ required: true, message: "请输入总分", trigger: "blur" }],
  duration: [{ required: true, message: "请输入考试时长", trigger: "blur" }],
  questions: [{ required: true, message: "请添加题目", trigger: "change" }],
};

// 对话框标题
const dialogTitle = computed(() => {
  return dialogType.value === "add" ? "新增试卷" : "编辑试卷";
});

// 获取试卷列表
const getList = async () => {
  loading.value = true;
  try {
    const { records, total: totalCount } = await getExamPapers(queryParams);
    paperList.value = records;
    total.value = totalCount;
  } catch (error) {
    console.error("获取试卷列表失败：", error);
  } finally {
    loading.value = false;
  }
};

// 查询按钮点击
const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

// 重置按钮点击
const resetQuery = () => {
  queryParams.paperName = "";
  queryParams.subject = "";
  queryParams.status = "";
  handleQuery();
};

// 分页大小改变
const handleSizeChange = (val) => {
  queryParams.pageSize = val;
  getList();
};

// 页码改变
const handleCurrentChange = (val) => {
  queryParams.pageNum = val;
  getList();
};

// 获取难度标签类型
const getDifficultyType = (difficulty) => {
  switch (difficulty) {
    case "EASY":
      return "success";
    case "MEDIUM":
      return "warning";
    case "HARD":
      return "danger";
    default:
      return "info";
  }
};

// 获取难度文本
const getDifficultyText = (difficulty) => {
  switch (difficulty) {
    case "EASY":
      return "简单";
    case "MEDIUM":
      return "中等";
    case "HARD":
      return "困难";
    default:
      return "未知";
  }
};

// 新增按钮点击
const handleAdd = () => {
  dialogType.value = "add";
  resetForm();
  dialogVisible.value = true;
};

// 编辑按钮点击
const handleEdit = (row) => {
  dialogType.value = "edit";
  resetForm();
  Object.assign(form, row);
  dialogVisible.value = true;
};

// 删除按钮点击
const handleDelete = (row) => {
  ElMessageBox.confirm("确认删除该试卷吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    try {
      await deleteExamPaper(row.id);
      ElMessage.success("删除成功");
      getList();
    } catch (error) {
      console.error("删除试卷失败：", error);
    }
  });
};

// 发布按钮点击
const handlePublish = (row) => {
  ElMessageBox.confirm("确认发布该试卷吗？发布后将不能修改", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    try {
      await publishExamPaper(row.id);
      ElMessage.success("发布成功");
      getList();
    } catch (error) {
      console.error("发布试卷失败：", error);
    }
  });
};

// 查看详情按钮点击
const handleViewDetail = (row) => {
  router.push(`/exam/paper/${row.id}`);
};

// 重置表单
const resetForm = () => {
  form.id = undefined;
  form.paperName = "";
  form.subject = "";
  form.totalScore = 100;
  form.duration = 60;
  form.questions = [];
};

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (dialogType.value === "add") {
          await addExamPaper(form);
          ElMessage.success("新增成功");
        } else {
          await updateExamPaper(form.id, form);
          ElMessage.success("修改成功");
        }
        dialogVisible.value = false;
        getList();
      } catch (error) {
        console.error("保存试卷失败：", error);
      }
    }
  });
};

// 选择题目相关
const questionDialogVisible = ref(false);
const questionLoading = ref(false);
const questionList = ref([]);
const questionTotal = ref(0);
const selectedQuestions = ref([]);
const questionTableRef = ref(null);
const questionQueryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  subject: "",
  difficulty: "",
});

// 添加题目按钮点击
const handleAddQuestion = () => {
  questionQueryParams.subject = form.subject;
  questionDialogVisible.value = true;
  getQuestionList();
};

// 获取题目列表
const getQuestionList = async () => {
  questionLoading.value = true;
  try {
    const { records, total: totalCount } = await getQuestions(
      questionQueryParams
    );
    questionList.value = records;
    questionTotal.value = totalCount;
  } catch (error) {
    console.error("获取题目列表失败：", error);
  } finally {
    questionLoading.value = false;
  }
};

// 搜索题目
const searchQuestions = () => {
  questionQueryParams.pageNum = 1;
  getQuestionList();
};

// 题目分页大小改变
const handleQuestionSizeChange = (val) => {
  questionQueryParams.pageSize = val;
  getQuestionList();
};

// 题目页码改变
const handleQuestionCurrentChange = (val) => {
  questionQueryParams.pageNum = val;
  getQuestionList();
};

// 题目选择改变
const handleQuestionSelectionChange = (selection) => {
  selectedQuestions.value = selection;
};

// 确认选择题目
const confirmSelectQuestions = () => {
  if (selectedQuestions.value.length === 0) {
    ElMessage.warning("请选择题目");
    return;
  }
  form.questions.push(...selectedQuestions.value);
  questionDialogVisible.value = false;
  selectedQuestions.value = [];
  if (questionTableRef.value) {
    questionTableRef.value.clearSelection();
  }
};

// 移除题目
const handleRemoveQuestion = (index) => {
  form.questions.splice(index, 1);
};

// 规则生成相关
const ruleDialogVisible = ref(false);
const ruleFormRef = ref(null);
const ruleForm = reactive({
  paperName: "",
  subject: "",
  duration: 60,
  rules: [
    {
      difficulty: "EASY",
      count: 5,
      score: 2,
    },
  ],
});

// 规则表单校验规则
const ruleRules = {
  paperName: [{ required: true, message: "请输入试卷名称", trigger: "blur" }],
  subject: [{ required: true, message: "请输入科目", trigger: "blur" }],
  duration: [{ required: true, message: "请输入考试时长", trigger: "blur" }],
};

// 规则生成按钮点击
const handleGenerateByRule = () => {
  ruleDialogVisible.value = true;
};

// 添加规则
const addRule = () => {
  ruleForm.rules.push({
    difficulty: "EASY",
    count: 5,
    score: 2,
  });
};

// 移除规则
const removeRule = (index) => {
  ruleForm.rules.splice(index, 1);
};

// 生成试卷
const generatePaper = async () => {
  if (!ruleFormRef.value) return;
  await ruleFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await generateExamPaper(ruleForm);
        ElMessage.success("生成成功");
        ruleDialogVisible.value = false;
        getList();
      } catch (error) {
        console.error("生成试卷失败：", error);
      }
    }
  });
};

onMounted(() => {
  getList();
});
</script>

<style scoped>
.toolbar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.search-form {
  flex: 1;
}

.toolbar-buttons {
  display: flex;
  gap: 10px;
  align-items: flex-start;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.question-toolbar {
  margin-bottom: 10px;
}

.unit-text {
  margin-left: 10px;
  color: #666;
}

.question-search {
  margin-bottom: 20px;
}

.question-pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.rule-item {
  display: flex;
  gap: 10px;
  align-items: center;
  margin-bottom: 10px;
}

.rule-add {
  margin-top: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
